package com.yinhai.activity;


import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.LoginTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.constant.UrlConstant;
import com.yinhai.service.CloudNoteServiceImpl;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.IMSI;
import com.yinhai.util.UuId;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ZDRegisterActivity （注册）
 * 
 * @author lixh
 */
public class ZDRegisterActivity extends Activity {
	String SENT_SMS_ACTION = "SENT_SMS_ACTION";
	private String uuid="";
	String userName="";
	private List<String> telList = new ArrayList<String>();
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    private AQuery aq = null;
    private long exitTime = 0;
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zd_register);
        aq = new AQuery(this);
        context = this;
        aq.id(R.id.zd_btn).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	 Intent sentIntent = new Intent(SENT_SMS_ACTION);
                 PendingIntent sentPI = PendingIntent.getBroadcast(ZDRegisterActivity.this, 0, sentIntent, 0);
                 SmsManager smsManager = SmsManager.getDefault();
                 telList.add("106571236");
                 uuid=UuId.getUUID();
                 ArrayList<String> divideContents = smsManager.divideMessage(uuid.trim());
                 if (divideContents.size() == 1) {
                     for (String text : divideContents) {
                         for (String str : telList) {
                             smsManager.sendTextMessage(str, null, text, sentPI, null);
                         }
                     }
                 }
                 new LocalContactAsyncTask().execute();
            }
        });
        
        aq.id(R.id.sd_btn).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                startActivity(new Intent(ZDRegisterActivity.this, LoginForPwdActivity.class));
            }
        });
        
        registerReceiver(loginreceiver, new IntentFilter("com.gaa.login2"));
        registerReceiver(loginreceiver1, new IntentFilter("com.gaa.login"));
    }

    public void doBack(View view) {
        onBackPressed();
    }
    
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
       if(event.getAction()==KeyEvent.ACTION_DOWN&&event.getKeyCode()==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0) {
           exit();
          return true;
       }
       return super.dispatchKeyEvent(event);
    }
    public void exit(){
        if((System.currentTimeMillis()-exitTime) > 2000){   
            Toast toast = Toast.makeText(getApplicationContext(), "再按一次后退键退出应用程序", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            exitTime = System.currentTimeMillis();    
        }else{   
            android.os.Process
            .killProcess(android.os.Process
                    .myPid());
        }
    }

    
ProgressDialog progressDialog = null;
    
    private class LocalContactAsyncTask extends AsyncTask<Void, Void, Integer> {
        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            progressDialog.cancel();
            if(1==result) {
            	Toast.makeText(context, "自动注册失败!", Toast.LENGTH_SHORT).show();
            }else {
            	Toast.makeText(context, "注册成功!", Toast.LENGTH_SHORT).show();
            }
        }
        
        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }
        
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progressDialog = new ProgressDialog(context);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("正在注册请等待!");
            progressDialog.show();
            // super.onPreExecute();
        }
        
        @Override
        protected Integer doInBackground(Void... arg0) {
        	int flag = 0;
            try {
				Thread.sleep(10000);
				userName = getPhone(uuid);
				Intent mIntent1 = new Intent("com.gaa.login2");
				context.sendBroadcast(mIntent1);
				Thread.sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
				flag = 1;
			}
            return flag;
        }
        
    }
    
private String getPhone(String uuid) throws Exception  {
	HttpPost httpRequest = getHttpPost(UrlConstant.PHONE_LOCAL_URI);
	List<NameValuePair> paramsUrl = new ArrayList<NameValuePair>();
	paramsUrl.add(new BasicNameValuePair("phoneKey", uuid));
	String resonsContent = "";
		// 发出HTTP request
		httpRequest.setEntity(new UrlEncodedFormEntity(paramsUrl,
				HTTP.UTF_8));
		// 取得HTTP response
		HttpResponse httpResponse = new DefaultHttpClient()
				.execute(httpRequest);
		// 若状态码为200 ok

		if (httpResponse.getStatusLine().getStatusCode() == 401) {
		} else if (httpResponse.getStatusLine().getStatusCode() != 200) {
		}
		Header[] headers = httpResponse.getHeaders("Content-Encoding");
		// 取出响应字符串
		resonsContent = EntityUtils.toString(httpResponse.getEntity());
	resonsContent.trim();
	return resonsContent;
}
private HttpPost getHttpPost(String url) {
	// 建立HTTP Post联机
	HttpPost httpRequest = new HttpPost(url);
	return httpRequest;
}   
private void LoadDengLu() {
        
        LoginTask loginTask = new LoginTask(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.CHECK);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        NameValueParam first = new NameValueParam();
        first.setName("first");
        // 第一次登录验证
        first.setValue("0");
        user_phone.setName("user_phone");
        user_phone.setValue(userName);
        NameValueParam imsinvp = new NameValueParam();
        NameValueParam flagnvp = new NameValueParam();
        String imsi = "";
        String flag = "";
        if (IMSI.getIMSI(context) != null) {
            imsi = IMSI.getIMSI(context);
            flag = "1";
        } else {
            imsi = UuId.getUUID();
            flag = "0";
        }
        imsinvp.setName("sim");
        imsinvp.setValue(imsi);
        flagnvp.setName("flag");
        flagnvp.setValue(flag);
        list.add(imsinvp);
        list.add(flagnvp);
        list.add(first);
        list.add(user_phone);
        taskParam.setPostParam(list);
        loginTask.execute(taskParam);
        runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
                CloudNoteServiceImpl cloudNoteService = new CloudNoteServiceImpl(ZDRegisterActivity.this);
                cloudNoteService.deleteAllCloudNote();
                ContactUserServiceImpl c = new ContactUserServiceImpl(ZDRegisterActivity.this);
                c.initOnlineContactLogin(userName);
            }
        });
        
    }

private BroadcastReceiver loginreceiver = new BroadcastReceiver() {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("com.gaa.login2")) {
        	LoadDengLu();
//        	try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//            finish();
        }
        
    }
};
private BroadcastReceiver loginreceiver1 = new BroadcastReceiver() {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals("com.gaa.login")) {
//			LoadDengLu();
//        	try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
            finish();
		}
		
	}
};

@Override
public void onDestroy() {
    unregisterReceiver(loginreceiver);
    unregisterReceiver(loginreceiver1);
    super.onDestroy();
}

}
